extends Node
var side:BoardCommon.TURN=BoardCommon.TURN.BLACK ## ai方 默认黑方
var pieces:Array[PieceV2] = [] ## 当前棋盘所有棋子
var validatorResource:Resource = preload("res://Board/Script/validate_controller.gd") ## 移动校验资源
var validator:ValidatorController ## 移动校验控制器
@onready var gameEvaluationResource:Resource = preload("res://Board/Script/game_evaluation.gd")
var gameEvaluation:GameEvaluation ## 游戏局势评估
## 初始化
func _ready() -> void:
	GlobalSignals.all_pieces_response_signal.connect(_on_all_pieces_request_signal)
	validator=validatorResource.new()
	gameEvaluation=gameEvaluationResource.new()
	print("ChatAI 初始化完成")

## 获取当前方 所有棋子可以移动的位置 获取每个棋子移动的最大分数
func get_all_piece_moves() -> Array[Dictionary]:
	GlobalSignals.all_pieces_request_signal.emit() ## 请求获取所有棋子

	var pieceMoves:Array[Dictionary] = []
	for piece in pieces:
		if piece && side==piece.side:
			for pos in BoardCommon.board_grid_pos():
				# 排除本方棋子的自身位置
				var grid_pos:Vector2i=BoardCommon.pos_to_grid_pos(piece.position)
				if grid_pos==pos:
					continue
				else :
					# 获取棋子当前位置到目标位置的合法性和移动价值
					var isValidator = validator.validate_piece(piece,grid_pos,pos)
					if isValidator:
						# 获取棋子移动的价值
						var score:int = gameEvaluation.move_score(piece.side,piece.type,grid_pos,pos) # 计算移动得分
						pieceMoves.append({
							"piece": piece,
							"from_pos": grid_pos,
							"to_pos": pos,
							"score": score
						})
	return pieceMoves

## 响应获取所有棋子信号
func _on_all_pieces_request_signal(all_pieces:Array[PieceV2]) -> void:
	pieces=all_pieces

## ai移动
func _ai_move() -> Dictionary:
	## 获取最大的分数移动
	var moves:Array[Dictionary] = get_all_piece_moves()
	moves.sort_custom(func(a, b): return a['score'] > b['score'])
	var useMove:Dictionary
	for move in moves:
		if move['piece']:
			useMove=move
			break
	# 执行分数最高的移动
	var piece:PieceV2 =  useMove['piece'] # 棋子
	var from_pos:Vector2i =useMove['from_pos'] # 起始位置
	var to_pos:Vector2i = useMove['to_pos'] # 目标位置

	return {
		piece = piece,
		from_pos = from_pos,
		to_pos = to_pos
	}
